﻿using System;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Timer = System.Windows.Forms.Timer;

namespace WinFormsApp_PowerOff_Reboot_etc
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.KeyUp += new KeyEventHandler(Form1_KeyUp);
            this.LostFocus += new EventHandler(Form1_LostFocus);

            this.ShowInTaskbar = false;

            ContextMenuStrip ctx1 = new ContextMenuStrip();
            ctx1.Items.Add("打开主界面");
            ctx1.Items.Add("退出");
            ctx1.ItemClicked += new ToolStripItemClickedEventHandler(ctx1_ItemClicked);
            notifyIcon1.ContextMenuStrip = ctx1;

            //初始化下拉框数据
            cbxPowerOffTimeMinutes.Items.Clear();
            cbxPowerOffTimeHour.Items.Clear();
            for (int i = 59; i >= 0; i--)
            {
                cbxPowerOffTimeMinutes.Items.Add(i.ToString());
            }
            for (int i = 23; i >= 0; i--)
            {
                cbxPowerOffTimeHour.Items.Add(i.ToString());
            }
            cbxPowerOffTimeMinutes.Text = 30.ToString();
            cbxPowerOffTimeHour.Text = 0.ToString();
        }

        void ctx1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.ToString() == "打开主界面")
            {
                this.Visible = true;
                WindowState = FormWindowState.Normal;
            }
            else if (e.ClickedItem.ToString() == "退出")
            {
                this.Close();
            }
        }

        private void btnCloseMonitor_Click(object sender, EventArgs e)
        {
            MyControl.CloseMonitor(this.Handle);
        }
        void Form1_LostFocus(object sender, EventArgs e)
        {
            MyControl.OpenMonitor(this.Handle);
        }

        bool IsMonitorClose = false;
        void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (IsMonitorClose)
                    MyControl.OpenMonitor(this.Handle);
                else
                    MyControl.CloseMonitor(this.Handle);
                IsMonitorClose = !IsMonitorClose;
            }
            else if (e.KeyCode == Keys.P)//关机
            {
                MyControl.PowerOff();
            }
            else if (e.KeyCode == Keys.R)//重启
            {
                MyControl.Reboot();
            }
            else if (e.KeyCode == Keys.L)//注销
            {
                MyControl.LogOff();
            }
            else if (e.KeyCode == Keys.C)
            {
                MyControl.OpenMonitor(this.Handle);
                this.Close();
            }

        }

        private void btnPowerOff_Click(object sender, EventArgs e)
        {
            MyControl.PowerOff();
        }

        private void btnReBoot_Click(object sender, EventArgs e)
        {
            MyControl.Reboot();
        }

        private void btnLogOff_Click(object sender, EventArgs e)
        {
            MyControl.LogOff();
        }

        private void btnCloseForm_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private Timer TimerPowerOff;//= new Timer();

        /// <summary>
        /// 默认关机时间(分钟)
        /// </summary>
        int TimeMinutes = 1;

        private void btnPowerOffSet_Click(object sender, EventArgs e)
        {
            string strPowerOffTime = cbxPowerOffTimeHour.SelectedItem.ToString();
            if (string.IsNullOrEmpty(strPowerOffTime)) return;

            #region 取得默认关机时间

            if (cbxPowerOffTimeHour.SelectedItem != null && cbxPowerOffTimeMinutes.SelectedItem == null)
            {
                cbxPowerOffTimeMinutes.SelectedItem = "0";
            }
            else if (cbxPowerOffTimeHour.SelectedItem == null && cbxPowerOffTimeMinutes.SelectedItem != null)
            {
                cbxPowerOffTimeHour.SelectedItem = "0";
            }
            int minutes = 0;
            minutes = Convert.ToInt32(cbxPowerOffTimeHour.SelectedItem.ToString()) * 60
                + Convert.ToInt32(cbxPowerOffTimeMinutes.SelectedItem.ToString());

            TimeMinutes = minutes;

            #endregion

            if (TimeMinutes == 0)
            {
                TimerPowerOff_Tick(sender, e);
                return;
            }
            if (TimerPowerOff != null)
                TimerPowerOff.Dispose();
            TimerPowerOff = new Timer();
            TimerPowerOff.Interval = 1000 * 60 * TimeMinutes;
            TimerPowerOff.Tick += TimerPowerOff_Tick;
            TimerPowerOff.Start();

            CheckForIllegalCrossThreadCalls = false;
            AsyncMethod_NoticePowerOffTimeLeft();//异步提醒关机时间

            lblCmdResult.Text = "设置关机成功！" + TimeMinutes / 60 + "小时" + TimeMinutes % 60 + "分钟后关机！";

            //strPowerOffTime = dateTimePicker1.Value.Hour + ":" + dateTimePicker1.Value.Minute;
            //string strCmd = "at " + strPowerOffTime + ":02" + " Shutdown -s";
            //if (!LstPowerOffTime.Contains(strPowerOffTime))
            //    LstPowerOffTime.Add(strPowerOffTime);
            //string returnStr = MyControl.ExecuteCmd(strCmd, 1000);
            //lblCmdResult.Text += "\n" + returnStr + " 在" + strPowerOffTime + " 关机";
        }

        void TimerPowerOff_Tick(object sender, EventArgs e)
        {
            //关机
            MyControl.PowerOff();
            TimerPowerOff.Enabled = false;
        }

        private Thread Thread1;
        public void AsyncMethod_NoticePowerOffTimeLeft()
        {
            ThreadStart threadStarter =
                () =>
                {
                    int t = TimeMinutes * 60 * 1;
                    int temp = TimeMinutes;
                    while (t >= 1)
                    {
                        Thread.Sleep(1000);
                        t = t - 1;
                        int minuteLeft, secondLeft;
                        minuteLeft = t / 60;
                        secondLeft = (t % 60);
                        if (minuteLeft == 0)
                        {
                            lblCmdResult.Text = secondLeft + "秒后关机！";
                        }
                        else if (minuteLeft > 60)
                        {
                            lblCmdResult.Text = minuteLeft / 60 + "小时" + minuteLeft % 60 + "分钟" + secondLeft + "秒后关机！";
                        }
                        else
                            lblCmdResult.Text = minuteLeft + "分钟" + secondLeft + "秒后关机！";
                        if (temp != TimeMinutes)//关机时间被修改，退出该线程的关机提示
                        {
                            break;
                        }
                    }
                };
            Thread1 = new Thread(threadStarter);
            Thread1.SetApartmentState(ApartmentState.STA);
            Thread1.Start();
        }

        private void btnPowerOffCancel_Click(object sender, EventArgs e)
        {
            //Thread1.Interrupt();
            TimeMinutes = 0;
            if (Thread1 != null)
                Thread1.Abort();
            if (TimerPowerOff != null)
                TimerPowerOff.Enabled = false;
            lblCmdResult.Text = "取消关机成功！";

        }
        #region 阻止系统关机

        //private bool canClose = true;
        //public const int WM_QUERYENDSESSION = 0x11;//要截获的关机消息
        //internal const int EWX_LOGOFF = 0x00000000;
        //internal const int EWX_SHUTDOWN = 0x00000001;
        //internal const int EWX_REBOOT = 0x00000002;
        //internal const int EWX_FORCE = 0x00000004;
        //internal const int EWX_POWEROFF = 0x00000008;
        //protected override void WndProc(ref Message m)//实现windows消息
        //{
        //    if (m.Msg == WM_QUERYENDSESSION || // m.Msg == 0x34 ||
        //                 m.Msg == 17)//0x34 重启、   关机、注销17
        //    {
        //        m.Result = new IntPtr(0);//０不关闭程序和系统；１关闭程序及系统
        //        canClose = false;

        //        //else
        //        //{
        //        //    m.Result = new IntPtr(1);//０不关闭程序和系统；１关闭程序及系统
        //        //    canClose = true;//可以关闭本窗口
        //        //}
        //    }
        //    base.WndProc(ref m);
        //}

        //protected override void OnClosing(CancelEventArgs e)
        //{
        //    //if (!canClose)
        //    //{
        //    //if (IsPreventPowerOff)
        //    //    e.Cancel = true;
        //    //}
        //    base.OnClosing(e);
        //    //还原回来，等到下一次收到消息会设置标记的，如果不是，正常情况也要可以关闭。
        //    canClose = true;
        //}

        #endregion

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
                this.Visible = false;
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Visible = true;
                WindowState = FormWindowState.Normal;
            }
        }

        /// <summary>
        /// 是否是数字
        /// </summary>
        static bool IsNumeric(string input)
        {
            bool flag = true;
            string pattern = (@"^\d+$");
            Regex validate = new Regex(pattern);

            if (!validate.IsMatch(input))
            {
                flag = false;
            }
            return flag;
        }

    }
}
